<?php
namespace com\rs\dns\controller\api\validate;

use com\rs\dns\constant\IpTableConstant;
use com\rs\dns\exception\BaException;
use restphp\exception\RestException;
use restphp\http\RestHttpStatus;
use restphp\utils\RestStringUtils;

/**
 * Class ValidateHost
 * @package com\rs\dns\controller\api\validate
 */
final class ValidateHost {
    /**
     * 参数是否正确.
     * @param $value
     * @param $message
     * @param $propName
     * @param $classInstance
     * @throws BaException
     * @throws RestException
     */
    public static function batchTxt($value, $message, $propName, $classInstance) {
        $value = trim($value);
        if (RestStringUtils::isBlank($value)) {
            if (RestStringUtils::isBlank($message)) {
                throw new BaException(IpTableConstant::IP_BATCH_TXT_ERROR);
            }
            throw new RestException($message, APP_NAME.'/'.IpTableConstant::IP_BATCH_TXT_ERROR, RestHttpStatus::Bad_Request, array($propName));
        }

        $arrLine = explode("\n", $value);
        foreach ($arrLine as $line) {
            $arrCol = explode(':', $line);
            if (count($arrCol) != 2) {
                if (RestStringUtils::isBlank($message)) {
                    throw new BaException(IpTableConstant::IP_BATCH_TXT_ERROR);
                }
                throw new RestException($message, APP_NAME.'/'.IpTableConstant::IP_BATCH_TXT_ERROR, RestHttpStatus::Bad_Request, array($propName));
            }

            if (!RestStringUtils::isIpv4($arrCol[0])) {
                if (RestStringUtils::isBlank($message)) {
                    throw new BaException(IpTableConstant::IP_BATCH_TXT_ERROR);
                }
                throw new RestException($message, APP_NAME.'/'.IpTableConstant::IP_BATCH_TXT_ERROR, RestHttpStatus::Bad_Request, array($propName));
            }

            if (!is_numeric($arrCol[1]) || $arrCol[1] < 0) {
                if (RestStringUtils::isBlank($message)) {
                    throw new BaException(IpTableConstant::IP_BATCH_TXT_ERROR);
                }
                throw new RestException($message, APP_NAME.'/'.IpTableConstant::IP_BATCH_TXT_ERROR, RestHttpStatus::Bad_Request, array($propName));
            }
        }
    }
}